package com.richpencil.modules.system.rest;

import com.richpencil.config.ProjectConfigInfo;
import com.richpencil.modules.system.domain.ImageObject;
import com.richpencil.modules.system.domain.PageParamInfo;
import com.richpencil.modules.system.domain.PageWeb;
import com.richpencil.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@Slf4j
public class BaseController {

    public String getSelectOptions(String values, String names) throws Exception {
        return uHtml.getSelectOptions(values, names);
    }

    public void setWxerrorMap(ModelMap map, String message, String voteid, String userid) {
        map.put("Msg", message);
        map.put("message", message);
        map.put("votehtml", "");//this.projectInfo.weixinauthorizeurl);
        map.put("voteid", voteid);
        map.put("userid", userid);
        map.put("success", false);
    }
    @Autowired
    public ProjectConfigInfo projectInfo;


    public boolean checkisTestMode(HttpServletRequest request)
    {
        String RequestUrl = request.getRequestURL().toString();
        boolean ret = true;
        if (RequestUrl.contains(this.projectInfo.vueurl) ||RequestUrl.contains("192.168"))
        {
            ret = true;
        } else {
            ret = false;
        } return ret;
    }


    public boolean checkistest(HttpServletRequest request)
    {
        if(projectInfo.isdebugmode()==true)
        {
            return true;
        } else
        {
            return false;
        }
    }
    public String getViewRedirectUrl(HttpServletRequest request)
    {
        if (this.checkistest(request)) {
            return this.projectInfo.vueurl;
        } else {
            return this.projectInfo.vueurl;
        }

    }
    public String getViewFrontUrl(HttpServletRequest request,String factionid,long fuserid,long fuseridiv)
    {
        String vueurl=this.RedirectObject(factionid,fuserid, fuseridiv);

        return vueurl;
    }



    private String RedirectObject(String factionid, long fuserid,long fuseridiv) {
        String fronturl = this.projectInfo.vueurl;
        String vueurl = "redirect:" + fronturl + "/?factionid=" + factionid
                + "&fuserid=" + String.valueOf(fuserid)
                + "&fuseridiv=" + String.valueOf(fuseridiv)
                + "&t=" + System.currentTimeMillis();
        return vueurl;
    }



    protected PageParamInfo setPageInfo(Integer page, Integer limit){
        PageParamInfo p=new PageParamInfo();
        p.setPageInfo(page, limit);
        return p;
    }

    protected void Printer(HttpServletResponse response, String value) throws IOException {
        response.getWriter().print(value);;
    }

    protected String decode(String value) throws UnsupportedEncodingException
    {
        String result = value.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
        result= java.net.URLDecoder.decode(result, "UTF-8");
        return result;

    }

    public int getIntParameter(HttpServletRequest request,String value)
    {
        String valueStr=this.getParameter(request, value);
        return IntegerHelper.getIntValue(valueStr);
    }

    public int getBooleanParameter(HttpServletRequest request,String value)
    {
        String valueStr=this.getParameter(request, value);
        return BooleanHelper.getIntValue(valueStr);
    }


    protected String getParameter(HttpServletRequest request,String value){
        return request.getParameter(value) ==null ? "" : request.getParameter(value).toString();
    }

    protected String getFormParameter(HttpServletRequest request,String value){
        return request.getParameter(value) ==null ? "" : request.getParameter(value).toString();
    }

    protected Integer getParameterIntDefault(HttpServletRequest request,String value,String defaultvalue){
        return Integer.parseInt(getParameterDefault(request,value,defaultvalue));
    }

    protected String getParameterDefault(HttpServletRequest request,String value,String defaultvalue){
        return request.getParameter(value) ==null ? defaultvalue : request.getParameter(value).toString();
    }

    protected String getPageNum(HttpServletRequest request){
        return request.getParameter("pagenum") ==null ? "1" : request.getParameter("pagenum").toString();
    }

    protected String getPageSize(HttpServletRequest request){
        return request.getParameter("pagesize") ==null ? "20" : request.getParameter("pagesize").toString();
    }

    protected PageWeb getRequestPageDefault(HttpServletRequest request)
    {
        PageWeb pageweb=new PageWeb();
        Integer pagenumber=this.getParameterIntDefault(request, "pagenum", "1");
        Integer pagesize=this.getParameterIntDefault(request, "pagesize", "10");
        pageweb.setPagenumber(pagenumber);
        pageweb.setPagesize(pagesize);
        return pageweb;
    }



    //添加异常日志
    protected void addException(Exception ex,String  FModuleId){

    }

    //添加错误日志
    protected void addErrorMethodLog(HttpServletRequest request,String Message){

    }
    public void  setUTF8(HttpServletResponse response)
    {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setContentType("application/json");

    }
    public PageWeb getPageNumberAndSize(Integer start, Integer length) {
        Integer pageNumber = start / length + 1;
        Integer pageSize = length;

        PageWeb PageWeb = new PageWeb();
        PageWeb.setPagenumber(pageNumber);
        PageWeb.setPagesize(pageSize);
        return PageWeb;
    }


    public void print(String value)
    {


        log.info("**************************************"+ DateUtils.GetCurrentDateTime());
        //System.out.println("**************************************"+DateUtils.GetCurrentDateTime());
        log.info(value);
        log.info("**************************************");

    }

    public void logerror(Exception ex)
    {
        log.error(ex.toString());
    }

    public void loginfo(String value)
    {
        log.info("********************************************"+DateUtils.GetCurrentDate());
        log.info(value);
        log.info("********************************************");
    }

    public void ResponseWrite(HttpServletResponse response, String value) throws IOException {
        response.getWriter().write(value);
    }

    public String getPayload(HttpServletRequest request){
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /*	public String saveImage(String imagedata)
        {
            String serverUrl=this.projectInfo.imagepathserver;
            String path=this.projectInfo.uploadpath;
            //System.out.println(path);
            byte[] dataBuf = Base64.decodeBase64(imagedata);
            String picName = IdHelper.GetImageFileName();
            try {
                ImageHelper.saveFileByInputStreamByArray(dataBuf, path, picName);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String imageUrl = serverUrl+"/"+"images"+"/"+picName;
            return imageUrl;
        }*/
    public String saveImageByMultipartFile(MultipartFile file) throws Exception
    {
        String serverUrl = this.projectInfo.uepath();
        String path = this.projectInfo.uepath;
        String imageUrl = "";
        String fileName = IdHelper.GetImageFileName();
        try {
            InputStream is = file.getInputStream();
            boolean success = ImageHelper.saveFileByInputStream(is, path, fileName);
            imageUrl = serverUrl  +"/" + fileName;
        } catch (IOException ex) {
        }
        return imageUrl;

    }

    public String getUrlByState(Integer state,HttpServletRequest request) {
        String RedirectUrl="";
        switch (state) {

            case 1:


                    RedirectUrl = this.projectInfo.authorizeurl;

                break;
            case 2:
                break;
        }
        return RedirectUrl;
    }

    public ImageObject saveImageObjectByMultipartFile(MultipartFile file) throws Exception
    {
        ImageObject ret=new ImageObject();

        String serverUrl = this.projectInfo.uepath;
        String path = this.projectInfo.uepath;
        String imageUrl = "";
        String fileName = IdHelper.GetImageFileName();
        try {
            InputStream is = file.getInputStream();
            boolean success = ImageHelper.saveFileByInputStream(is, path, fileName);
            imageUrl = serverUrl  +"/" + fileName;
            ret.imageserverurl=imageUrl;
            ret.imagelocalurl=path+ File.separator+fileName;

        } catch (IOException ex) {
        }
        return ret;

    }

}
